<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title>销售流程管理</title>
    <style>
        .process-container {
            padding: 20px;
        }
        .process-card {
            margin-bottom: 20px;
            border: 1px solid #eee;
            border-radius: 5px;
            padding: 15px;
        }
        .process-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .process-default {
            background-color: #e7f5ff;
            border-left: 4px solid var(--primary-color);
        }
        .process-stages {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .stage-item {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 8px 15px;
            font-size: 14px;
            flex-grow: 1;
            text-align: center;
            position: relative;
        }
        .stage-item::after {
            content: "→";
            position: absolute;
            right: -5px;
            top: 50%;
            transform: translateY(-50%);
        }
        .stage-item:last-child::after {
            content: "";
        }
        .modal-body {
            max-height: 500px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="process-container">
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">销售流程管理</h2>
                    <button class="btn btn-primary" onclick="showAddProcessModal()">添加销售流程</button>
                </div>
                <div class="card-body">
                    <div id="process-list">
                        <!-- 示例销售流程 -->
                        <div class="process-card process-default">
                            <div class="process-header">
                                <h3>标准销售流程</h3>
                                <span class="badge badge-primary">默认</span>
                            </div>
                            <p>适用于大多数销售场景的标准流程</p>
                            <div class="process-stages">
                                <div class="stage-item">初步接触</div>
                                <div class="stage-item">需求分析</div>
                                <div class="stage-item">方案制定</div>
                                <div class="stage-item">报价谈判</div>
                                <div class="stage-item">成交</div>
                            </div>
                            <div class="d-flex justify-content-end mt-3">
                                <button class="btn btn-sm btn-info mr-2" onclick="viewProcess(1)">查看</button>
                                <button class="btn btn-sm btn-primary mr-2" onclick="editProcess(1)">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteProcess(1)">删除</button>
                            </div>
                        </div>
                        
                        <div class="process-card">
                            <div class="process-header">
                                <h3>简化销售流程</h3>
                            </div>
                            <p>适用于小额快速交易的简化流程</p>
                            <div class="process-stages">
                                <div class="stage-item">接触</div>
                                <div class="stage-item">报价</div>
                                <div class="stage-item">成交</div>
                            </div>
                            <div class="d-flex justify-content-end mt-3">
                                <button class="btn btn-sm btn-info mr-2" onclick="viewProcess(2)">查看</button>
                                <button class="btn btn-sm btn-primary mr-2" onclick="editProcess(2)">编辑</button>
                                <button class="btn btn-sm btn-secondary mr-2" onclick="setAsDefault(2)">设为默认</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteProcess(2)">删除</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 添加/编辑销售流程模态框 -->
        <div id="processModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
            <div style="background-color: white; margin: 5% auto; width: 600px; border-radius: 5px; overflow: hidden;">
                <div style="background-color: var(--primary-color); color: white; padding: 15px 20px;">
                    <h3 id="modalTitle">添加销售流程</h3>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <form id="processForm">
                        <div class="form-group">
                            <label for="processName">流程名称</label>
                            <input type="text" class="form-control" id="processName" required>
                        </div>
                        <div class="form-group">
                            <label for="processDescription">流程描述</label>
                            <textarea class="form-control" id="processDescription" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label>销售阶段</label>
                            <div id="stageContainer">
                                <div class="d-flex mb-2 stage-row">
                                    <input type="text" class="form-control mr-2" placeholder="阶段名称" required>
                                    <input type="number" class="form-control mr-2" placeholder="顺序" style="width: 80px;" required>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="removeStage(this)">删除</button>
                                </div>
                            </div>
                            <button type="button" class="btn btn-sm btn-secondary mt-2" onclick="addStage()">添加阶段</button>
                        </div>
                    </form>
                </div>
                <div style="padding: 15px 20px; border-top: 1px solid #eee; text-align: right;">
                    <button class="btn btn-secondary mr-2" onclick="closeModal()">取消</button>
                    <button class="btn btn-primary" onclick="saveProcess()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script>
            let processes = []; // 存储所有流程数据
            
            // 页面加载完成后获取数据
            document.addEventListener('DOMContentLoaded', function() {
                loadProcesses();
            });
            
            // 从API加载所有流程
            function loadProcesses() {
                fetch('/crm/api/sales/process/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            processes = result.data;
                            renderProcesses();
                        } else {
                            showToast('加载销售流程失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error loading processes:', error);
                        showToast('加载销售流程失败', 'error');
                    });
            }
            
            // 渲染流程列表
            function renderProcesses() {
                const container = document.getElementById('process-list');
                container.innerHTML = '';
                
                if (processes.length === 0) {
                    container.innerHTML = '<div class="alert alert-info">暂无销售流程，请添加一个新流程</div>';
                    return;
                }
                
                processes.forEach(process => {
                    const isDefault = process.isDefault === 1;
                    const div = document.createElement('div');
                    div.className = `process-card ${isDefault ? 'process-default' : ''}`;
                    
                    let stagesHtml = '';
                    if (process.stages && process.stages.length > 0) {
                        // 按照顺序排序阶段
                        const sortedStages = [...process.stages].sort((a, b) => a.order - b.order);
                        stagesHtml = sortedStages.map(stage => 
                            `<div class="stage-item">${stage.name}</div>`
                        ).join('');
                    }
                    
                    div.innerHTML = `
                        <div class="process-header">
                            <h3>${process.name}</h3>
                            ${isDefault ? '<span class="badge badge-primary">默认</span>' : ''}
                        </div>
                        <p>${process.description || ''}</p>
                        <div class="process-stages">
                            ${stagesHtml}
                        </div>
                        <div class="d-flex justify-content-end mt-3">
                            <button class="btn btn-sm btn-info mr-2" onclick="viewProcess(${process.id})">查看</button>
                            <button class="btn btn-sm btn-primary mr-2" onclick="editProcess(${process.id})">编辑</button>
                            ${!isDefault ? `<button class="btn btn-sm btn-secondary mr-2" onclick="setAsDefault(${process.id})">设为默认</button>` : ''}
                            <button class="btn btn-sm btn-danger" onclick="deleteProcess(${process.id})">删除</button>
                        </div>
                    `;
                    
                    container.appendChild(div);
                });
            }

            function showAddProcessModal() {
                document.getElementById('modalTitle').textContent = '添加销售流程';
                document.getElementById('processForm').reset();
                
                // 清除所有已添加的阶段，只保留一个
                const stageContainer = document.getElementById('stageContainer');
                stageContainer.innerHTML = `
                    <div class="d-flex mb-2 stage-row">
                        <input type="text" class="form-control mr-2" placeholder="阶段名称" required>
                        <input type="number" class="form-control mr-2" placeholder="顺序" style="width: 80px;" value="1" required>
                        <button type="button" class="btn btn-danger btn-sm" onclick="removeStage(this)">删除</button>
                    </div>
                `;
                
                document.getElementById('processModal').style.display = 'block';
            }
            
            function editProcess(id) {
                document.getElementById('modalTitle').textContent = '编辑销售流程';
                
                // 通过API获取流程详情
                fetch(`/crm/api/sales/process/${id}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200 && result.data) {
                            const process = result.data;
                            
                            // 填充表单数据
                            document.getElementById('processName').value = process.name;
                            document.getElementById('processDescription').value = process.description || '';
                            
                            // 设置表单的数据属性，用于标识是编辑操作
                            document.getElementById('processForm').setAttribute('data-id', process.id);
                            
                            // 添加阶段
                            const stageContainer = document.getElementById('stageContainer');
                            stageContainer.innerHTML = '';
                            
                            if (process.stages && process.stages.length > 0) {
                                // 按照顺序排序阶段
                                const sortedStages = [...process.stages].sort((a, b) => a.order - b.order);
                                
                                sortedStages.forEach(stage => {
                                    const stageDiv = document.createElement('div');
                                    stageDiv.className = 'd-flex mb-2 stage-row';
                                    stageDiv.innerHTML = `
                                        <input type="text" class="form-control mr-2" placeholder="阶段名称" value="${stage.name}" required>
                                        <input type="number" class="form-control mr-2" placeholder="顺序" style="width: 80px;" value="${stage.order}" required>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeStage(this)">删除</button>
                                    `;
                                    stageContainer.appendChild(stageDiv);
                                });
                            } else {
                                // 如果没有阶段，添加一个空白阶段
                                addStage();
                            }
                            
                            document.getElementById('processModal').style.display = 'block';
                        } else {
                            showToast('获取流程详情失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error loading process details:', error);
                        showToast('获取流程详情失败', 'error');
                    });
            }
            
            function viewProcess(id) {
                // 通过API获取流程详情并显示
                fetch(`/crm/api/sales/process/${id}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200 && result.data) {
                            const process = result.data;
                            alert(`流程名称: ${process.name}\n描述: ${process.description || '无'}\n阶段数: ${process.stages ? process.stages.length : 0}`);
                        } else {
                            showToast('获取流程详情失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error viewing process:', error);
                        showToast('获取流程详情失败', 'error');
                    });
            }
            
            function deleteProcess(id) {
                if (confirm("确定要删除此销售流程吗？")) {
                    // 调用API删除流程
                    fetch(`/crm/api/sales/process/${id}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            showToast('删除流程成功', 'success');
                            loadProcesses(); // 重新加载流程列表
                        } else {
                            showToast('删除流程失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting process:', error);
                        showToast('删除流程失败', 'error');
                    });
                }
            }
            
            function setAsDefault(id) {
                if (confirm("确定要将此流程设为默认吗？")) {
                    // 调用API设置默认流程
                    fetch(`/crm/api/sales/process/default/${id}`, {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            showToast('设置默认流程成功', 'success');
                            loadProcesses(); // 重新加载流程列表
                        } else {
                            showToast('设置默认流程失败: ' + result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error setting default process:', error);
                        showToast('设置默认流程失败', 'error');
                    });
                }
            }
            
            function addStage() {
                const stageContainer = document.getElementById('stageContainer');
                const stageCount = stageContainer.querySelectorAll('.stage-row').length;
                
                const stageDiv = document.createElement('div');
                stageDiv.className = 'd-flex mb-2 stage-row';
                stageDiv.innerHTML = `
                    <input type="text" class="form-control mr-2" placeholder="阶段名称" required>
                    <input type="number" class="form-control mr-2" placeholder="顺序" style="width: 80px;" value="${stageCount + 1}" required>
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeStage(this)">删除</button>
                `;
                stageContainer.appendChild(stageDiv);
            }
            
            function removeStage(button) {
                const stageRow = button.closest('.stage-row');
                const stageContainer = document.getElementById('stageContainer');
                
                // 如果只有一个阶段，不允许删除
                if (stageContainer.querySelectorAll('.stage-row').length > 1) {
                    stageRow.remove();
                    
                    // 重新排序
                    const rows = stageContainer.querySelectorAll('.stage-row');
                    rows.forEach((row, index) => {
                        row.querySelector('input[type="number"]').value = index + 1;
                    });
                } else {
                    alert("销售流程至少需要一个阶段");
                }
            }
            
            function closeModal() {
                document.getElementById('processModal').style.display = 'none';
            }
            
            function saveProcess() {
                const form = document.getElementById('processForm');
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                const processId = form.getAttribute('data-id');
                const processName = document.getElementById('processName').value;
                const processDescription = document.getElementById('processDescription').value;
                
                const stages = [];
                document.querySelectorAll('.stage-row').forEach(row => {
                    stages.push({
                        name: row.querySelector('input[type="text"]').value,
                        orderNum: parseInt(row.querySelector('input[type="number"]').value),
                        description: "", // 添加描述字段
                        winRate: 50, // 添加默认的赢单率
                        requiredFields: "", // 添加必填字段列表
                        expectedDays: 7 // 添加预期完成天数
                    });
                });
                
                const processData = {
                    name: processName,
                    description: processDescription,
                    isDefault: false, // 添加默认值
                    stages: stages
                };
                
                // 如果是编辑操作，添加ID
                if (processId) {
                    processData.id = processId;
                }
                
                // 发送数据到服务器
                const url = processId ? '/crm/api/sales/process/update' : '/crm/api/sales/process';
                const method = processId ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(processData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        showToast(`${processId ? '更新' : '添加'}流程成功`, 'success');
                        closeModal();
                        loadProcesses(); // 重新加载流程列表
                    } else {
                        showToast(`${processId ? '更新' : '添加'}流程失败: ` + result.message, 'error');
                    }
                })
                .catch(error => {
                    console.error(`Error ${processId ? 'updating' : 'adding'} process:`, error);
                    showToast(`${processId ? '更新' : '添加'}流程失败`, 'error');
                });
            }
        </script>
    </th:block>
</body>
</html> 